package com.atilim.cargo.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;

import com.atilim.cargo.business.AdministrationBean;
import com.atilim.cargo.business.AuthorizationBean;
import com.atilim.cargo.business.CargoManagementBean;
import com.atilim.cargo.business.ValidationBean;
import com.atilim.cargo.business.VechileManagementBean;
import com.atilim.cargo.model.Cargo;
import com.atilim.cargo.model.Customer;
import com.atilim.cargo.model.User;
import com.atilim.cargo.model.Vechile;


/**
 * Servlet implementation class AdministrationServlet
 */
@WebServlet("/AdministrationServlet")
public class AdministrationServlet extends BaseServlet {
	

	@Inject
	AdministrationBean administrationBean;
	
	@Inject
	ValidationBean validationBean;
	
	@Inject
	VechileManagementBean vechileManagementBean;
	
	@Inject
	AuthorizationBean authorizationBean;
	
	@Inject
	CargoManagementBean cargoManagementBean;
	
	@Override
	public void execute(HttpServletRequest req, HttpServletResponse resp)
			throws Exception {
		String cmd = req.getParameter("cmd");
		
		if ("searchVechile".equals(cmd)) {
			searchVechile(req, resp);
		} else if ("saveVechile".equals(cmd)) {
			saveVechile(req, resp);
		} else if ("getVechile".equals(cmd)) {
			getVechile(req, resp);
		} else if ("saveUser".equals(cmd)) {
			saveUser(req, resp);
		} else if ("searchUser".equals(cmd)) {
			searchUser(req, resp);
		} else if ("getUser".equals(cmd)) {
			getUser(req, resp);
		} else if ("saveCargo".equals(cmd)) {
			saveCargo(req, resp);
		} else if ("searchCustomer".equals(cmd)) {
			searchCustomer(req, resp);
		} else if ("saveCustomer".equals(cmd)) {
			saveCustomer(req, resp);
		} else if ("searchCargo".equals(cmd)) {
			searchCargo(req, resp);
		} else if ("addCargoIntoVechile".equals(cmd)) {
			addCargoIntoVechile(req, resp);
		} else if ("removeCargoFromVechile".equals(cmd)) {
			removeCargoFromVechile(req, resp);
		} else if ("deliverCargo".equals(cmd)) {
			deliverCargo(req, resp);
		} 
		
	}

	private void deliverCargo(HttpServletRequest req, HttpServletResponse resp)
			throws Exception {
		String cargoIds = req.getParameter("cargoIds");
		
		JSONObject obj = new JSONObject();

		if (cargoIds != null && !"".equals(cargoIds)) {
			
			JSONArray arr = new JSONArray(cargoIds);
			long [] cargoIdArr = new long [arr.length()];
			for (int i = 0; i < arr.length(); i++) {
				cargoIdArr[i] = Long.parseLong(arr.get(i).toString());
			}
			cargoManagementBean.deliverCargo(cargoIdArr);
			
			obj.put("msg", arr.length() + " adet kargo müşteriye teslim edildi");
			obj.put("success", true);	
		} else {
			obj.put("msg", "cargoIds boş");
			obj.put("success", false);	
		}
		
		resp.getWriter().write(obj.toString());

	}

	private void removeCargoFromVechile(HttpServletRequest req, HttpServletResponse resp)
			throws Exception {
		String cargoIds = req.getParameter("cargoIds");
		
		JSONObject obj = new JSONObject();

		if (cargoIds != null && !"".equals(cargoIds)) {
			
			JSONArray arr = new JSONArray(cargoIds);
			long [] cargoIdArr = new long [arr.length()];
			for (int i = 0; i < arr.length(); i++) {
				cargoIdArr[i] = Long.parseLong(arr.get(i).toString());
			}
			cargoManagementBean.removeCargoFromVechile(cargoIdArr);
			
			obj.put("msg", arr.length() + " adet kargo araçtan çıkarıldı");
			obj.put("success", true);	
		} else {
			obj.put("msg", "cargoIds boş");
			obj.put("success", false);	
		}
		
		resp.getWriter().write(obj.toString());

	}
	
	private void addCargoIntoVechile(HttpServletRequest req, HttpServletResponse resp)
			throws Exception {
		String cargoIds = req.getParameter("cargoIds");
		String vechileId = req.getParameter("vechileId");
		
		JSONObject obj = new JSONObject();

		if (cargoIds != null && !"".equals(cargoIds)) {
			
			JSONArray arr = new JSONArray(cargoIds);
			long [] cargoIdArr = new long [arr.length()];
			for (int i = 0; i < arr.length(); i++) {
				cargoIdArr[i] = Long.parseLong(arr.get(i).toString());
			}
			cargoManagementBean.addCargoIntoVechile(cargoIdArr, Long.parseLong(vechileId));
			
			obj.put("msg", arr.length() + " adet kargo araca yüklendi");
			obj.put("success", true);	
		} else {
			obj.put("msg", "cargoIds boş");
			obj.put("success", false);	
		}
		
		resp.getWriter().write(obj.toString());

	}
	
	
	private void getUser(HttpServletRequest req, HttpServletResponse resp)
			throws Exception {
		String id = req.getParameter("id");
		
		JSONObject obj = new JSONObject();

		if (id != null && !"".equals(id)) {
			User user = authorizationBean.getUser(Long.parseLong(id));
			JSONObject data = new JSONObject();
			data.put("id", id);
			data.put("name", user.getName());
			data.put("surname", user.getSurname());
			data.put("username", user.getUsername());
			data.put("password", user.getPassword());
			data.put("type", user.getType());
			obj.put("data", data);
			obj.put("success", true);	
		} else {
			obj.put("msg", "ID tanımsız");
			obj.put("success", false);	
		}
		
		resp.getWriter().write(obj.toString());

	}
	
	private void getVechile(HttpServletRequest req, HttpServletResponse resp)
			throws Exception {
		String id = req.getParameter("id");
		
		JSONObject obj = new JSONObject();

		if (id != null && !"".equals(id)) {
			Vechile vechile = vechileManagementBean.getVechile(Long.parseLong(id));
			JSONObject data = new JSONObject();
			data.put("id", id);
			data.put("capacity", vechile.getCapacity());
			data.put("plateNo", vechile.getPlateNo());
			obj.put("data", data);
			obj.put("success", true);	
		} else {
			obj.put("msg", "ID tanımsız");
			obj.put("success", false);	
		}
		
		resp.getWriter().write(obj.toString());

	}
	
	private void saveUser(HttpServletRequest req, HttpServletResponse resp)
			throws Exception {

		String id = req.getParameter("id");
		String username = req.getParameter("username");
		String name = req.getParameter("name");
		String surname = req.getParameter("surname");
		String password = req.getParameter("password");
		int type = Integer.parseInt(req.getParameter("type"));
		
		User user = null;
		if (id != null && !"".equals(id)) {
			user = authorizationBean.getUser(Long.parseLong(id));
		} else {
			user = new User();
		}
		user.setUsername(username);
		user.setName(name);
		user.setPassword(password);
		user.setSurname(surname);
		user.setType(type);
		
		JSONObject obj = new JSONObject();
		if (!validationBean.validateUser(user)) { //kullanıcı bilgileri doğrulanmadyısa
			obj.put("msg", "Kullanıcı bilgilerini doğru giriniz");
			obj.put("success", false);
		} else {
			if (id != null && !"".equals(id)) {
				administrationBean.updateUser(user);
			} else {
				administrationBean.insertUser(user);				
			}
			obj.put("msg", "Kullanıcı kaydedildi");
			obj.put("success", true);			
		}
		
		resp.getWriter().write(obj.toString());
		
	}

	
	private void saveCargo(HttpServletRequest req, HttpServletResponse resp)
			throws Exception {

		String id = req.getParameter("id");
		String sWeight = req.getParameter("weight");
		String targetPhone = req.getParameter("targetPhone");
		String targetAddress = req.getParameter("targetAddress");
		String targetPerson = req.getParameter("targetPerson");
		String sCustomerId = req.getParameter("customerId");
		
		double weight = 0.0;
		if (sWeight != null && !"".equals(sWeight)) {
			weight = Double.parseDouble(sWeight);
		}
		
		Cargo cargo = null;
		if (id != null && !"".equals(id)) {
			cargo = cargoManagementBean.getCargo(Long.parseLong(id));
		} else {
			cargo = new Cargo();
		}
		cargo.setTargetAddress(targetAddress);
		cargo.setCustomerId(Long.parseLong(sCustomerId));
		cargo.setTargetPerson(targetPerson);
		cargo.setTargetPhone(targetPhone);
		cargo.setWeight(weight);
		
		JSONObject obj = new JSONObject();
		if (!validationBean.validateCargo(cargo)) { //kargo bilgileri doğrulanmadyısa
			obj.put("msg", "Kargo bilgilerini doğru giriniz");
			obj.put("success", false);
		} else {
			if (id != null && !"".equals(id)) {
				cargoManagementBean.updateCargo(cargo);
			} else {
				cargoManagementBean.insertCargo(cargo);
			}
			obj.put("msg", "Kargo kaydedildi");
			obj.put("success", true);			
		}
		
		resp.getWriter().write(obj.toString());
		
	}

	private void searchVechile(HttpServletRequest req, HttpServletResponse resp)
			throws Exception {
		Map<String, Object> queryParams = new HashMap<String, Object>();
		if (req.getParameter("plateNo") != null) {
			queryParams.put("plateNo", req.getParameter("plateNo"));
		}
		List<Vechile> list = vechileManagementBean.searchVechile(queryParams);
		
		JSONObject obj = new JSONObject();
		JSONArray arr = new JSONArray();
		for (Vechile vechile : list) {
			JSONObject o = new JSONObject();
			o.put("id", vechile.getId());
			o.put("plateNo", vechile.getPlateNo());
			o.put("capacity", vechile.getCapacity());
			arr.put(o);
		}
		obj.put("items", arr);
		obj.put("success", true);
		
		resp.getWriter().write(obj.toString());
		
	}
	
	private void searchUser(HttpServletRequest req, HttpServletResponse resp)
			throws Exception {
		
		Map<String, Object> queryParams = new HashMap<String, Object>();
		if (req.getParameter("name") != null) {
			queryParams.put("name", req.getParameter("name"));
		}
		if (req.getParameter("surname") != null) {
			queryParams.put("surname", req.getParameter("surname"));
		}
		
		List<User> list = administrationBean.searchUser(queryParams);
		
		JSONObject obj = new JSONObject();
		JSONArray arr = new JSONArray();
		for (User vechile : list) {
			JSONObject o = new JSONObject();
			o.put("id", vechile.getId());
			o.put("name", vechile.getName());
			o.put("surname", vechile.getSurname());
			o.put("username", vechile.getUsername());
			o.put("type", vechile.getType());
			arr.put(o);
		}
		obj.put("items", arr);
		obj.put("success", true);
		
		resp.getWriter().write(obj.toString());
		
	}

	
	private void searchCustomer(HttpServletRequest req, HttpServletResponse resp)
			throws Exception {
		
		Map<String, Object> queryParams = new HashMap<String, Object>();
		if (req.getParameter("name") != null) {
			queryParams.put("name", req.getParameter("name"));
		}
		if (req.getParameter("surname") != null) {
			queryParams.put("surname", req.getParameter("surname"));
		}
		if (req.getParameter("tckn") != null) {
			queryParams.put("tckn", req.getParameter("tckn"));
		}
		
		List<Customer> list = administrationBean.searchCustomer(queryParams);
		
		JSONObject obj = new JSONObject();
		JSONArray arr = new JSONArray();
		for (Customer customer : list) {
			JSONObject o = new JSONObject();
			o.put("id", customer.getId());
			o.put("name", customer.getName());
			o.put("surname", customer.getSurname());
			o.put("phone", customer.getPhone());
			o.put("tckn", customer.getTckn());
			o.put("text", customer.toString());
			arr.put(o);
		}
		obj.put("items", arr);
		obj.put("success", true);

		if (req.getParameterMap().containsKey("query")) { //combodan çağrıldığı anlamına gelir
			resp.getWriter().write(arr.toString());
			return;
		}
		
		resp.getWriter().write(obj.toString());
		
	}

	
	private void searchCargo(HttpServletRequest req, HttpServletResponse resp)
			throws Exception {
		
		Map<String, Object> queryParams = new HashMap<String, Object>();
		if (req.getParameter("name") != null) {
			queryParams.put("name", req.getParameter("name"));
		}
		if (req.getParameter("surname") != null) {
			queryParams.put("surname", req.getParameter("surname"));
		}
		if (req.getParameter("tckn") != null) {
			queryParams.put("tckn", req.getParameter("tckn"));
		}
		
		List<Cargo> list = cargoManagementBean.searchCargo(queryParams);
		
		JSONObject obj = new JSONObject();
		JSONArray arr = new JSONArray();
		for (Cargo cargo: list) {
			JSONObject o = new JSONObject();
			o.put("id", cargo.getId());
			o.put("customerId", cargo.getCustomerId());
			o.put("status", cargo.getStatus());
			o.put("weight", cargo.getWeight());
			o.put("targetAddress", cargo.getTargetAddress());
			o.put("targetPerson", cargo.getTargetPerson());
			o.put("targetPhone", cargo.getTargetPhone());
			o.put("vechileId", cargo.getVechileId());
			arr.put(o);
		}
		obj.put("items", arr);
		obj.put("success", true);

		if (req.getParameterMap().containsKey("query")) { //combodan çağrıldığı anlamına gelir
			resp.getWriter().write(arr.toString());
			return;
		}
		
		resp.getWriter().write(obj.toString());
		
	}

	private void saveVechile(HttpServletRequest req, HttpServletResponse resp)
			throws Exception {
		Vechile vechile = new Vechile();
		String id = req.getParameter("id");
		String plateNo = req.getParameter("plateNo");
		int capacity = Integer.parseInt(req.getParameter("capacity"));
		vechile.setCapacity(capacity);
		vechile.setPlateNo(plateNo);
		
		JSONObject obj = new JSONObject();
		if (!validationBean.validateVechile(vechile)) {
			
			obj.put("success", true);
			obj.put("msg", "Araç bilgilerini doğru giriniz.");
			
		} else {
			
			if (id != null && !"".equals(id.trim())) {
				vechile.setId(Long.parseLong(id));
				vechileManagementBean.updateVechile(vechile);
			} else {
				vechileManagementBean.insertVechile(vechile);
			}		
			obj.put("success", true);
			obj.put("msg", "Başarıyla kaydedildi");
			
		}

		resp.getWriter().write(obj.toString());
		
	}
	
	private void saveCustomer(HttpServletRequest req, HttpServletResponse resp)
			throws Exception {

		String id = req.getParameter("id");
		String name = req.getParameter("name");
		String phone = req.getParameter("phone");
		String surname = req.getParameter("surname");
		String tckn = req.getParameter("tckn");
		
		Customer customer = null;
		if (id != null && !"".equals(id)) {
			customer = administrationBean.getCustomer(Long.parseLong(id));
		} else {
			customer = new Customer();
		}
		customer.setName(name);
		customer.setPhone(phone);
		customer.setSurname(surname);
		customer.setTckn(tckn);
		
		JSONObject obj = new JSONObject();
		if (!validationBean.validateCustomer(customer)) { //müşteri bilgileri doğrulanmadyısa
			obj.put("msg", "Müşteri bilgilerini doğru giriniz");
			obj.put("success", false);
		} else {
			if (id != null && !"".equals(id)) {
				administrationBean.updateCustomer(customer);
			} else {
				administrationBean.insertCustomer(customer);
			}
			obj.put("msg", "Müşteri kaydedildi");
			obj.put("success", true);			
		}
		
		resp.getWriter().write(obj.toString());
		
	}
       
}
